import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import type { IRootState } from './index'
import { Actions, Mutations } from '@/enum/card'
import { upsert, IUpsertParams, detail, IDetailParams } from '@/api/commonInstance'
import { DBNames } from '@/enum/dbName'

export interface ICard {
  createdBy: string
  createdTime: string
  customerId: string
  data: Record<string, unknown>
  id: string
  _id?: string // 临时兼容
  isDeleted: number
  orgId: string
  ownerId: string
  status?: string
  templateName: string
  updatedBy: string
  updatedTime: string
}
export interface ICardState {
  cardObj: ICard
}

export const state: () => ICardState = () => ({
  cardObj: {
    createdBy: '',
    createdTime: '',
    customerId: '',
    data: {},
    id: '',
    _id: '',
    isDeleted: 0,
    orgId: '',
    ownerId: '',
    status: '',
    templateName: '',
    updatedBy: '',
    updatedTime: '',
  },
})

export const mutations: MutationTree<ICardState> = {
  [Mutations.SET_CARD](state, payload) {
    state.cardObj = payload
  },
}

export const actions: ActionTree<ICardState, IRootState> = {
  async [Actions.getCard]({ commit }, cardId: string) {
    const params: IDetailParams = {
      id: cardId,
      templateName: DBNames.B_MARKETING_CARD,
    }

    let result: any = await detail(params)

    if (!result) {
      const upsertParams: IUpsertParams = {
        id: cardId,
        data: {
          showCommerce: true, // 是否显示商会
          showPark: true, // 是否显示园区
          showProject: true, // 是否显示项目
          showCarrier: true, // 是否显示资源
          showEnterprise: true, // 是否显示会员企业
          showMember: true, // 是否显示商会会员
          showInformation: true, // 是否显示商会动态
        },
        templateName: DBNames.B_MARKETING_CARD,
      }
      result = await upsert(upsertParams)
    }

    commit(Mutations.SET_CARD, result)

    return result
  },
}

export const getters: GetterTree<ICardState, IRootState> = {
  cardId: (state) => state.cardObj._id || state.cardObj.id,
  cardData: (state) => state.cardObj.data,
}
